import { openDB } from 'idb';
import { message } from 'ant-design-vue';

const dbPromise = openDB('gonganDB', 1, {
  upgrade(db) {
    if (!db.objectStoreNames.contains('govArea')) {
      db.createObjectStore('govArea', {
        keyPath: 'id',
        autoIncrement: true,
      });
    }
    
    if (!db.objectStoreNames.contains('govLine')) {
      db.createObjectStore('govLine', {
        keyPath: 'id',
        autoIncrement: true,
      });
    }
  },
});

export const saveItem = async (field='govArea', item) => {
  if (field == 'polygon') field = 'govArea'
  const db = await dbPromise;

  if (item.id) {
    // 如果项目包含 id，则更新项目
    message.success('数据已更新');
    return db.put(field, JSON.parse(JSON.stringify(item)));
  } else {
    // 如果项目不包含 id，则添加新项目
    message.success('数据已添加');
    return db.add(field, JSON.parse(JSON.stringify(item)));
  }
};

export const getItems = async (field='govArea') => {
  const db = await dbPromise;
  return db.getAll(field);
};

export const getItemById = async (field='govArea', id) => {
  const db = await dbPromise;
  return db.get(field, id);
};

export const updateItem = async (field='govArea', id, updatedItem) => {
  const db = await dbPromise;
  return db.put(field, { ...updatedItem, id });
};

export const deleteItem = async (field='govArea', id) => {
  const db = await dbPromise;
  return db.delete(field, id);
};
